﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Text;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace AOuSuisJe
{
    public delegate void ApiCallEndedEventHandler(object sender, EventArgs e);
    public delegate void ConnectionProblemEventHandler(object sender, EventArgs e);
    public class ApiUpload
    {
        public event ApiCallEndedEventHandler ApiCallEnded;
        public event ConnectionProblemEventHandler ConnectionProblem;
        private string api_server = "http://www.findwhere.me/OuSuisJe/";
        private Stream StrToUpload;

        public void Upload(string name,Stream photo)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(api_server + "Enigmas/UploadFile/"+name);
            req.Method = "POST";
            StrToUpload = photo ;
            req.BeginGetRequestStream(new AsyncCallback(OnRequestCallbackFile), req); 
            //reqStream = FileUpload1.PostedFile.InputStream;
            //FileUpload1.FileContent.CopyTo(reqStream);
            //req.GetResponse();
        }
        private string JsonToUpload;
        public void CreateEnigma(Enigma enig)
        {
            JsonToUpload=JsonConvert.SerializeObject(enig);
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(api_server+ "Enigmas");
            req.Method = "POST";
            req.ContentType = @"application/json"; 
            req.Accept = @"application/json"; 
            req.BeginGetRequestStream(new AsyncCallback(OnRequestCallback), req); 
        }
        public void AuthenticateUser(string email,byte[] password)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(api_server + "AuthenticateUser");
            
            string txt="";
            for (int i = 0; i < password.Length; i++)
            {
                if (i != 0)
                    txt = txt + ",";
                txt = txt + password[i];
            }
           
            JsonToUpload = "{\"email\":\""+email+"\",\"password\":[" +txt+ "]}";
            req.Method = "POST";
            req.ContentType = @"application/json";
            req.Accept = @"application/json";
            req.BeginGetRequestStream(new AsyncCallback(OnRequestCallback), req); 
        }

        public Dictionary<string,string> Params {get;set;}
        private string http_build_query(Dictionary<string, string> param)
        {
            string strRetVal = "";

            if (param.Count > 0)
            {
                foreach (KeyValuePair<string, string> s in param)
                {
                    strRetVal += HttpUtility.UrlEncode(s.Key) + "=" + HttpUtility.UrlEncode(s.Value) + "&";
                }
                strRetVal = strRetVal.Substring(0, strRetVal.Length - 1);
            }

            return strRetVal;
        }
        private void OnRequestCallback(IAsyncResult result)
        {
            HttpWebRequest request = ((HttpWebRequest)result.AsyncState);
            
            
            // End the operation 
            Stream postStream = request.EndGetRequestStream(result);
            request.ContentType = @"application/json";
            request.Accept = @"application/json"; 
            // Write to the request stream.
            postStream.Write(Encoding.UTF8.GetBytes(JsonToUpload), 0, JsonToUpload.Length);
            postStream.Close();

            // Start the asynchronous operation to get the response
            request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);

        }
        private void OnRequestCallbackFile(IAsyncResult result)
        {
            HttpWebRequest request = ((HttpWebRequest)(result.AsyncState));

            Stream postStream = request.EndGetRequestStream(result);
            byte[] tabstr = new Byte[StrToUpload.Length];

            StrToUpload.Read(tabstr, 0, (int)StrToUpload.Length);
            // Write to the request stream.
            postStream.Write(tabstr, 0, tabstr.Length);
            postStream.Close();
            //}
            // Start the asynchronous operation to get the response
            request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);

        }
        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            try{
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            string responseBody;
            using (var stream = response.GetResponseStream())
            {
                //fd = jss.ReadObject(stream) as FaceRestAPI.FaceAPI;
                var reader = new StreamReader(stream, Encoding.UTF8);
                responseBody = reader.ReadToEnd();
            }
            if (ApiCallEnded != null)
            {
                ApiCallEnded(responseBody, EventArgs.Empty);

            }
            }
            catch (Exception e)
            {
                if (ConnectionProblem != null)
                {
                    ConnectionProblem(null, EventArgs.Empty);
                }
            }
        }
    }
}
